<?php

namespace App\Http\Controllers;
use App\Models\Test\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index(){
//    $user = User::find(1);
//    return $this->response->array(['name'=>'hjj','age'=>'11']);//响应数组
//        return $this->response->item($user,new UserTranformer());//响应一个元素
        $users = User::all();
//
//        return $this->response->collection($users, new UserTransformer);//响应集合

//        $users = User::paginate(25);
//        return $this->response->paginator($users, new UserTransformer);//响应分页

        //->withHeader('X-Foo', 'Bar');加头信息
        return $this->response
            ->collection($users, new UserTransformer)
            ->withHeader('X-Foo', 'Bar')
            ->addMeta('foo', 'bar');//加meta  信息

    }

    public function home(){
        $url = app('Dingo\Api\Routing\UrlGenerator')->version('v1')->route('test.home');
        dd($url);
    }
    public function users(){
        $users = User::all();
        return $this->response
            ->collection($users, new UserTransformer);
    }
    public function login(Request $request){
//        dd(bcrypt('123456'));
//        $email = $request->input('email');
//        $password = $request->input('password');
        $credentials = request(['email', 'password']);  //直接全部获取

        if (!$token = auth('api')->attempt($credentials)) {
//            return response()->json(['error' => 'Unauthorized'], 401);   //默认
            // 一个未认证错误，第一个参数可以传递自定义消息。
            return $this->response->errorUnauthorized();
        }

        return $this->respondWithToken($token);

    }
    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            // return $this->respose->array()//放到里面去，生成一个数组响应
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }









}
